package com.whmskj.xjlhsc.mobie.Scheduling.Service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.util.StringUtil;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhbc.domain.CorpMember;
import com.whmskj.xjlhbc.domain.Yg01employeefiles;
import com.whmskj.xjlhbc.dto.JcQueryDto;
import com.whmskj.xjlhbc.mapper.CorpMemberMapper;
import com.whmskj.xjlhbc.service.IPersonnelManagementDataSheetsService;
import com.whmskj.xjlhsc.jitapi.dto.Emp;
import com.whmskj.xjlhsc.mapper.Yg01employeefilesMapper;
import com.whmskj.xjlhsc.mobie.Scheduling.Dto.PictureVo;
import com.whmskj.xjlhsc.mobie.Scheduling.Dto.RecordsOfEmployeeAwardsAndSancti;
import com.whmskj.xjlhsc.mobie.Scheduling.Service.RecordsOfEmployeeAwardsAndSanctiService;
import com.whmskj.xjlhsc.mobie.Scheduling.entity.yg01EmployeeFiles;
import com.whmskj.xjlhsc.mobie.Scheduling.mapper.EmployeeFilesMapper;
import com.whmskj.xjlhsc.mobie.Scheduling.mapper.RecordsOfEmployeeAwardsAndSanctiMapper;
import com.whmskj.xjlhsc.mobie.empProPlan.entity.ProPersonnelStandConfirm;
import com.whmskj.xjlhsc.utils.SCUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.format.DateTimeFormatters;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: Sakura
 * @Date: 2025/8/30 11:41
 * @Version: v1.0.0
 * @Description: TODO
 **/
@Service
public class RecordsOfEmployeeAwardsAndSanctiServiceImpl extends ServiceImpl<RecordsOfEmployeeAwardsAndSanctiMapper, RecordsOfEmployeeAwardsAndSancti>
        implements RecordsOfEmployeeAwardsAndSanctiService {

    @Autowired
    private CorpMemberMapper corpMemberMapper;

    @Autowired
    private EmployeeFilesMapper employeeFilesMapper;
    @Autowired
    private RecordsOfEmployeeAwardsAndSanctiMapper recordsOfEmployeeAwardsAndSanctiMapper;

    @Override
    public List<RecordsOfEmployeeAwardsAndSancti> queryList(JcQueryDto param) {
        List<RecordsOfEmployeeAwardsAndSancti> result=new ArrayList<>();
        List<RecordsOfEmployeeAwardsAndSancti>  allRecords=new ArrayList<>();
        if ("全部".equals(param.getStatus())) {
            param.setStatus(null);
        }
        if ("全部".equals(param.getClass55())) {
            param.setClass55(null);
        }
        if ("全部".equals(param.getProcess())){
            param.setProcess(null);
        }
        if ("全部".equals(param.getReason())){
            param.setReason(null);
        }

        Emp currentLoginEmp = SCUtil.getCurrentLoginEmp();

        if (currentLoginEmp.getPositions().contains("厂长") || currentLoginEmp.getPositions().equals("总经理")){
            param.setNickName(currentLoginEmp.getEmpName());
            param.setCanReview(1);

            LambdaQueryWrapper<Yg01employeefiles> yg01employeefilesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            if (currentLoginEmp.getPositions().contains("厂长")){
                yg01employeefilesLambdaQueryWrapper.like(Yg01employeefiles::getPositions,"总经理");
            }
            else {
                yg01employeefilesLambdaQueryWrapper.like(Yg01employeefiles::getPositions,"厂长");
            }

            Yg01employeefiles nickNameNot = yg01employeefilesMapper.selectOne(yg01employeefilesLambdaQueryWrapper);
            param.setNickNameNot(nickNameNot.getName());

            Page.startPage();
            allRecords = recordsOfEmployeeAwardsAndSanctiMapper.selectRecordsOfEmployeeAwardsAndSanctiList(param);

            allRecords.forEach(item -> {item.setCanApprove(true);});

        }
        if (StringUtil.isEmpty(param.getNickName())){
            String empName = currentLoginEmp.getEmpName();
            LambdaQueryWrapper<Yg01employeefiles> yg01employeefilesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            yg01employeefilesLambdaQueryWrapper.last(" where firstlevelReviewerForRewardsAndS like '%"+empName+"%'");
            Long count = yg01employeefilesMapper.selectCount(yg01employeefilesLambdaQueryWrapper);
            Assert.isTrue(count>0,"空空空空");
            param.setCanReview(2);
            param.setNickName(empName);

            Page.startPage();
            allRecords = recordsOfEmployeeAwardsAndSanctiMapper.selectRecordsOfEmployeeAwardsAndSanctiList(param);

            allRecords.forEach(item -> {item.setCanApprove(false);});
        }

        allRecords.forEach(item -> {
            String empPicture = item.getEmpPicture();
            if (StringUtil.isNotEmpty(empPicture)) {
                Integer startIndex = empPicture.indexOf("url:") + 8;
                Integer endIndex = empPicture.indexOf(",", startIndex);
                String substring = empPicture.substring(startIndex, endIndex);
                item.setEmpPicture(substring);
            }
        });

        Map<String, List<RecordsOfEmployeeAwardsAndSancti>> collect = allRecords.stream().collect(Collectors.groupingBy(RecordsOfEmployeeAwardsAndSancti::getStatus));
        // 添加 null 检查后再添加到结果中
        Optional.ofNullable(collect.get("未审核"))
                .ifPresent(list -> result.addAll(list));

        Optional.ofNullable(collect.get("已审核"))
                .ifPresent(list -> result.addAll(list));


        return result;

        // 过滤出每个记录的最新版本
//        Map<Integer, RecordsOfEmployeeAwardsAndSancti> latestVersions = new HashMap<>();
//        for (RecordsOfEmployeeAwardsAndSancti record : allRecords) {
//            // 确定记录的原始ID（如果是第一版，originalId为null，用id；否则用originalId）
//            Integer originalId = record.getOriginalId() != null ? record.getOriginalId() : record.getId();
//
//            // 如果这是第一版或者版本号比当前存储的版本更高，则更新
//            if (!latestVersions.containsKey(originalId) ||
//                    latestVersions.get(originalId).getVersion() < record.getVersion()) {
//                latestVersions.put(originalId, record);
//            }
//        }

        // 转换用户信息
//        List<RecordsOfEmployeeAwardsAndSancti> list = new ArrayList<>(latestVersions.values());
//        list.forEach(item -> {
//            // 转换 firstLevelReviewer 字段
//            String firstLevelReviewer = item.getFirstLevelReviewer();
//            if (StringUtils.hasText(firstLevelReviewer)) {
//                LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
//                wrapper.eq(CorpMember::getMemberId, firstLevelReviewer);
//                CorpMember member = corpMemberMapper.selectOne(wrapper);
//                if (member != null && StringUtils.hasText(member.getNick())) {
//                    item.setFirstLevelReviewer(member.getNick());
//                }
//            }
//
//            // 转换 secondLevelReviewer 字段
//            String secondLevelReviewer = item.getSecondLevelReviewer();
//            if (StringUtils.hasText(secondLevelReviewer)) {
//                LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
//                wrapper.eq(CorpMember::getMemberId, secondLevelReviewer);
//                CorpMember member = corpMemberMapper.selectOne(wrapper);
//                if (member != null && StringUtils.hasText(member.getNick())) {
//                    item.setSecondLevelReviewer(member.getNick());
//                }
//            }
//        });

        // 分页处理（如果需要）
//        Page.startPage();
    }

    @Autowired
    private Yg01employeefilesMapper yg01employeefilesMapper;

    @Override
    public boolean add(RecordsOfEmployeeAwardsAndSancti body) {
        //验证当前用户有没有权限
        Emp currentLoginEmp = SCUtil.getCurrentLoginEmp();
        Yg01employeefiles yg01employeefiles = yg01employeefilesMapper.selectById(body.getEmpId());
        if (!yg01employeefiles.getFirstlevelReviewerForRewardsAndS().contains(currentLoginEmp.getEmpName())){
            throw new RuntimeException("没有权限");
        }


//        CorpMember corpMember = getCorpMember();
//        if (corpMember == null) {
//            return false;
//        }

//        // 根据员工姓名自动填充员工信息
//        if (StringUtils.hasText(body.getName())) {
        fillEmployeeInfoByName(body);
//        }

        //增加员工工序

        // 获取最大单据编号
        RecordsOfEmployeeAwardsAndSancti max = baseMapper.selectMaxDocumentNumber();
        String maxDocumentNumber = max != null ? max.getDocumentNumber() : "202500000";

        // 使用用户的nick字段而不是memberId
        body.setFirstLevelReviewer(currentLoginEmp.getEmpName()); // 设置为用户昵称
        body.setDateTime(new Date());
        body.setTimeOfSubmission(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));//提交时间
        body.setModified(DateUtil.now());
        body.setDocumentNumber(String.valueOf(Integer.parseInt(maxDocumentNumber) + 1));

        if (StringUtil.isNotEmpty(body.getSecondLevelReviewer()) && body.getSecondLevelReviewer().equals("不需要")){
            body.setStatus("已审核");
            body.setSecondLevelReviewerName(body.getFirstLevelReviewer());
            body.setApprovalTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        }else {
            body.setStatus("未审核");
            LambdaQueryWrapper<Yg01employeefiles> yg01employeefilesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            yg01employeefilesLambdaQueryWrapper.like(Yg01employeefiles::getPositions,body.getSecondLevelReviewer());
            Yg01employeefiles yg01employeefiles1 = yg01employeefilesMapper.selectOne(yg01employeefilesLambdaQueryWrapper);
            body.setSecondLevelReviewerName(yg01employeefiles1.getName());
        }
        body.setReviewStatus("未复核");
        // 自动转换金额为大写
        if (body.getF28c() != null) {
            body.setAmountTotal1(convertToChineseYuan(body.getF28c()));
        }

        return save(body);
    }

    @Override
    public boolean approve(List<String> ids) {

        List<RecordsOfEmployeeAwardsAndSancti> list = listByIds(ids);
        Emp currentLoginEmp = SCUtil.getCurrentLoginEmp();
        for (RecordsOfEmployeeAwardsAndSancti recordsOfEmployeeAwardsAndSancti : list) {
            if (!recordsOfEmployeeAwardsAndSancti.getSecondLevelReviewerName().contains(currentLoginEmp.getEmpName())){
               throw new RuntimeException("没有权限");
            }
        }
        list.forEach(item -> {
            item.setStatus("已审核");
            item.setModified(DateUtil.now());
            item.setApprovalTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        });

        return updateBatchById(list);
    }

    @Override
    public boolean invalidate(List<String> ids) {

        if (ids == null || ids.isEmpty()) {
            return false;
        }

        List<RecordsOfEmployeeAwardsAndSancti> list = listByIds(ids);

        Assert.isTrue(CollectionUtil.isNotEmpty(list),"查询不到当前奖惩记录");

        Emp currentLoginEmp = SCUtil.getCurrentLoginEmp();

        for (RecordsOfEmployeeAwardsAndSancti recordsOfEmployeeAwardsAndSancti : list) {
            if ( !recordsOfEmployeeAwardsAndSancti.getSecondLevelReviewerName().contains(currentLoginEmp.getEmpName())){
                    throw new RuntimeException("没有权限");
            }
        }


        list.forEach(item -> {
            item.setStatus("作废");
            item.setModified(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            item.setApprovalTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        });

        return updateBatchById(list);
    }

    @Override
    public Map<String, Object> getCurrentUserStatistics() {
        CorpMember corpMember = getCorpMember();
        if (corpMember == null) {
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalCount", 0);// 总数
            statistics.put("approvedCount", 0);// 已审核数
            statistics.put("rewardAmount", 0.0);// 奖励金额
            statistics.put("punishmentAmount", 0.0);// 惩罚金额
            return statistics;
        }
        String currentUserId = corpMember.getNick();
        Map<String, Object> statistics = new HashMap<>();

        try {
            // 查询当前用户提交的所有记录
            List<RecordsOfEmployeeAwardsAndSancti> allRecords = lambdaQuery()
                    .eq(RecordsOfEmployeeAwardsAndSancti::getFirstLevelReviewer, currentUserId)
                    .list();

            // 统计总订单数
            int totalCount = allRecords.size();

            // 统计已审核订单数
            int approvedCount = (int) allRecords.stream()
                    .filter(record -> "已审核".equals(record.getStatus()))
                    .count();

            // 统计奖励金额
            double rewardAmount = allRecords.stream()
                    .filter(record -> "奖励".equals(record.getTypeOfAward()) && "已审核".equals(record.getStatus()))
                    .mapToDouble(record -> record.getF28c() != null ? record.getF28c().doubleValue() : 0.0)
                    .sum();

            // 统计处罚金额
            double punishmentAmount = allRecords.stream()
                    .filter(record -> "处罚".equals(record.getTypeOfAward()) && "已审核".equals(record.getStatus()))
                    .mapToDouble(record -> record.getF28c() != null ? record.getF28c().doubleValue() : 0.0)
                    .sum();

            statistics.put("totalCount", totalCount);
            statistics.put("approvedCount", approvedCount);
            statistics.put("rewardAmount", rewardAmount);
            statistics.put("punishmentAmount", -punishmentAmount); // 处罚金额显示为负数

        } catch (Exception e) {
            statistics.put("totalCount", 0);
            statistics.put("approvedCount", 0);
            statistics.put("rewardAmount", 0.0);
            statistics.put("punishmentAmount", 0.0);
        }

        return statistics;
    }

    @Override
    public Map<String, Object> getStatisticsOverview(String startDate, String endDate) {
        Map<String, Object> overview = new HashMap<>();

        try {
            LambdaQueryWrapper<RecordsOfEmployeeAwardsAndSancti> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RecordsOfEmployeeAwardsAndSancti::getStatus, "已审核");

            if (StringUtils.hasText(startDate)) {
                wrapper.ge(RecordsOfEmployeeAwardsAndSancti::getDateTime, startDate);
            }
            if (StringUtils.hasText(endDate)) {
                wrapper.le(RecordsOfEmployeeAwardsAndSancti::getDateTime, endDate);
            }

            List<RecordsOfEmployeeAwardsAndSancti> records = list(wrapper);

            double rewardAmount = 0.0;
            double punishmentAmount = 0.0;

            for (RecordsOfEmployeeAwardsAndSancti record : records) {
                BigDecimal amount = record.getF28c();
                if (amount != null) {
                    if ("奖励".equals(record.getTypeOfAward())) {
                        rewardAmount += amount.doubleValue();
                    } else if ("处罚".equals(record.getTypeOfAward())) {
                        punishmentAmount += amount.doubleValue();
                    }
                }
            }

            overview.put("reward", rewardAmount);
            overview.put("punishment", punishmentAmount);
            overview.put("total", rewardAmount - punishmentAmount);

        } catch (Exception e) {
            overview.put("reward", 0.0);
            overview.put("punishment", 0.0);
            overview.put("total", 0.0);
        }

        return overview;
    }

    @Override
    public List<Map<String, Object>> getWorkshopStatistics(String startDate, String endDate) {
        List<Map<String, Object>> workshopStats = new ArrayList<>();

        try {
            LambdaQueryWrapper<RecordsOfEmployeeAwardsAndSancti> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RecordsOfEmployeeAwardsAndSancti::getStatus, "已审核");

            if (StringUtils.hasText(startDate)) {
                wrapper.ge(RecordsOfEmployeeAwardsAndSancti::getDateTime, startDate);
            }
            if (StringUtils.hasText(endDate)) {
                wrapper.le(RecordsOfEmployeeAwardsAndSancti::getDateTime, endDate);
            }

            List<RecordsOfEmployeeAwardsAndSancti> records = list(wrapper);

            // 按车间分组统计
            Map<String, Map<String, Object>> workshopMap = new HashMap<>();

            for (RecordsOfEmployeeAwardsAndSancti record : records) {
                String workshop = record.getWorkshop();

                if (StringUtils.hasText(workshop)) {
                    workshopMap.computeIfAbsent(workshop, k -> {
                        Map<String, Object> stats = new HashMap<>();
                        stats.put("workshop", workshop);
                        stats.put("reward", 0.0);
                        stats.put("punishment", 0.0);
                        stats.put("total", 0.0);
                        return stats;
                    });

                    BigDecimal amount = record.getF28c();
                    if (amount != null) {
                        Map<String, Object> stats = workshopMap.get(workshop);

                        if ("奖励".equals(record.getTypeOfAward())) {
                            stats.put("reward", (Double) stats.get("reward") + amount.doubleValue());
                        } else if ("处罚".equals(record.getTypeOfAward())) {
                            stats.put("punishment", (Double) stats.get("punishment") + amount.doubleValue());
                        }
                    }
                }
            }

            // 计算合计
            for (Map<String, Object> stats : workshopMap.values()) {
                double reward = (Double) stats.get("reward");
                double punishment = (Double) stats.get("punishment");
                double total = reward - punishment;
                stats.put("total", total);
            }

            // 按合计金额排序
            workshopStats = workshopMap.values().stream()
                    .sorted((a, b) -> Double.compare((Double) b.get("total"), (Double) a.get("total")))
                    .collect(Collectors.toList());

        } catch (Exception e) {
            // 异常处理
        }

        return workshopStats;
    }

    @Override
    public List<Map<String, Object>> getTeamStatistics(String startDate, String endDate) {
        List<Map<String, Object>> teamStats = new ArrayList<>();

        try {
            LambdaQueryWrapper<RecordsOfEmployeeAwardsAndSancti> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RecordsOfEmployeeAwardsAndSancti::getStatus, "已审核");

            if (StringUtils.hasText(startDate)) {
                wrapper.ge(RecordsOfEmployeeAwardsAndSancti::getDateTime, startDate);
            }
            if (StringUtils.hasText(endDate)) {
                wrapper.le(RecordsOfEmployeeAwardsAndSancti::getDateTime, endDate);
            }

            List<RecordsOfEmployeeAwardsAndSancti> records = list(wrapper);

            // 按班组分组统计
            Map<String, Map<String, Object>> teamMap = new HashMap<>();

            for (RecordsOfEmployeeAwardsAndSancti record : records) {
                String team = record.getFa90();
                if (StringUtils.hasText(team)) {
                    teamMap.computeIfAbsent(team, k -> {
                        Map<String, Object> stats = new HashMap<>();
                        stats.put("team", k);
                        stats.put("reward", 0.0);
                        stats.put("punishment", 0.0);
                        stats.put("total", 0.0);
                        return stats;
                    });

                    BigDecimal amount = record.getF28c();
                    if (amount != null) {
                        Map<String, Object> stats = teamMap.get(team);

                        if ("奖励".equals(record.getTypeOfAward())) {
                            stats.put("reward", (Double) stats.get("reward") + amount.doubleValue());
                        } else if ("处罚".equals(record.getTypeOfAward())) {
                            stats.put("punishment", (Double) stats.get("punishment") + amount.doubleValue());
                        }
                    }
                }
            }

            // 计算合计并排序
            for (Map<String, Object> stats : teamMap.values()) {
                double reward = (Double) stats.get("reward");
                double punishment = (Double) stats.get("punishment");
                double total = reward - punishment;
                stats.put("total", total);
            }

            // 按合计金额倒序排列
            teamStats = teamMap.values().stream()
                    .sorted((a, b) -> Double.compare((Double) b.get("total"), (Double) a.get("total")))
                    .collect(Collectors.toList());

        } catch (Exception e) {
            // 异常处理
        }

        return teamStats;
    }

    @Override
    public List<Map<String, Object>> getEmployeeStatistics(String startDate, String endDate) {
        List<Map<String, Object>> employeeStats = new ArrayList<>();

        try {
            LambdaQueryWrapper<RecordsOfEmployeeAwardsAndSancti> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RecordsOfEmployeeAwardsAndSancti::getStatus, "已审核");

            if (StringUtils.hasText(startDate)) {
                wrapper.ge(RecordsOfEmployeeAwardsAndSancti::getDateTime, startDate);
            }
            if (StringUtils.hasText(endDate)) {
                wrapper.le(RecordsOfEmployeeAwardsAndSancti::getDateTime, endDate);
            }

            List<RecordsOfEmployeeAwardsAndSancti> records = list(wrapper);

            // 按员工分组统计
            Map<String, Map<String, Object>> employeeMap = new HashMap<>();

            for (RecordsOfEmployeeAwardsAndSancti record : records) {
                String employeeName = record.getName();
                if (StringUtils.hasText(employeeName)) {
                    employeeMap.computeIfAbsent(employeeName, k -> {
                        Map<String, Object> stats = new HashMap<>();
                        stats.put("employee", k);
                        stats.put("total", 0.0);
                        return stats;
                    });

                    BigDecimal amount = record.getF28c();
                    if (amount != null) {
                        Map<String, Object> stats = employeeMap.get(employeeName);
                        double currentTotal = (Double) stats.get("total");

                        if ("奖励".equals(record.getTypeOfAward())) {
                            stats.put("total", currentTotal + amount.doubleValue());
                        } else if ("处罚".equals(record.getTypeOfAward())) {
                            stats.put("total", currentTotal - amount.doubleValue());
                        }
                    }
                }
            }

            // 按合计金额倒序排列
            employeeStats = employeeMap.values().stream()
                    .sorted((a, b) -> Double.compare((Double) b.get("total"), (Double) a.get("total")))
                    .collect(Collectors.toList());

        } catch (Exception e) {
            // 异常处理
        }

        return employeeStats;
    }

    private CorpMember getCorpMember() {
        IPersonnelManagementDataSheetsService personnel = SpringUtil.getBean(IPersonnelManagementDataSheetsService.class);
        return personnel.getCorpMemberByLogin();
    }

    @Override
    public RecordsOfEmployeeAwardsAndSancti getByIdWithUserInfo(String id) {
        RecordsOfEmployeeAwardsAndSancti record = getById(id);
        if (record == null) {
            return null;
        }
        String livePicturesDto = record.getLivePicturesDto();
        // 将JSON字符串反序列化为List<PictureVo>
        List<PictureVo> pictureVoList = new ArrayList<>();
        if (StringUtil.isNotEmpty(livePicturesDto)) {
            pictureVoList = JSONUtil.toList(JSONUtil.parseArray(livePicturesDto), PictureVo.class);
        }

        List<String> livePicturesList = new ArrayList<>();
        for (PictureVo pictureVo : pictureVoList) {
            String url = pictureVo.getUrl();
            livePicturesList.add(url);
        }

        // 设置到record对象中
        record.setLivePictures(livePicturesList);
        record.setLivePicturesDto(null);

//        // 获取该记录的最新版本
//        Integer originalId = record.getOriginalId() != null ?
//                record.getOriginalId() : record.getId();
//
//        RecordsOfEmployeeAwardsAndSancti latestVersion = lambdaQuery()
//                .and(wrapper -> wrapper.eq(RecordsOfEmployeeAwardsAndSancti::getId, originalId)
//                        .or()
//                        .eq(RecordsOfEmployeeAwardsAndSancti::getOriginalId, originalId))
//                .orderByDesc(RecordsOfEmployeeAwardsAndSancti::getVersion)
//                .last("limit 1")
//                .one();
//
//        // 使用最新版本的记录
//        record = latestVersion;
//
//        // 转换 firstLevelReviewer 字段
//        String firstLevelReviewer = record.getFirstLevelReviewer();
//        if (StringUtils.hasText(firstLevelReviewer)) {
//            LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(CorpMember::getMemberId, firstLevelReviewer).last("limit 1");
//            CorpMember member = corpMemberMapper.selectOne(wrapper);
//            if (member != null && StringUtils.hasText(member.getNick())) {
//                record.setFirstLevelReviewer(member.getNick());
//            }
//        }
//
//        // 转换 secondLevelReviewer 字段
//        String secondLevelReviewer = record.getSecondLevelReviewer();
//        if (StringUtils.hasText(secondLevelReviewer)) {
//            LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(CorpMember::getMemberId, secondLevelReviewer).last("limit 1");
//            CorpMember member = corpMemberMapper.selectOne(wrapper);
//            if (member != null && StringUtils.hasText(member.getNick())) {
//                record.setSecondLevelReviewer(member.getNick());
//            }
//        }

        return record;
    }



    @Override
    @Transactional
    public boolean updateRecord(RecordsOfEmployeeAwardsAndSancti body) {
        Emp currentLoginEmp = SCUtil.getCurrentLoginEmp();

        Integer id = body.getId();
        RecordsOfEmployeeAwardsAndSancti beforeRecord = getById(id);

        if(StringUtil.isEmpty(beforeRecord.getStatus()) || "已审核".equals(beforeRecord.getStatus())){
            throw new RuntimeException("审核状态异常，或已审核");
        }

        if (!body.getFirstLevelReviewer().contains(currentLoginEmp.getEmpName())){
            throw new RuntimeException("没有权限");
        }

        List<String> livePictures = body.getLivePictures();
        List<PictureVo> pictureVoList=new ArrayList<>();
        if (CollectionUtil.isNotEmpty(livePictures)){
            for (String livePicture : livePictures) {
                PictureVo pictureVo = new PictureVo(livePicture);
                pictureVoList.add(pictureVo);
            }
        }
        String newLivePictures = JSONUtil.parse(pictureVoList).toString();
        body.setLivePicturesDto(newLivePictures);

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        body.setModified(LocalDate.now().format(dateTimeFormatter));
        return updateById(body);
//        CorpMember corpMember = getCorpMember();
//        if (corpMember == null) {
//            return false;
//        }
//
//        // 获取原始记录
//        RecordsOfEmployeeAwardsAndSancti originalRecord = getById(body.getId());
//        if (originalRecord == null) {
//            return false;
//        }
//
//        // 创建新记录对象
//        RecordsOfEmployeeAwardsAndSancti newRecord = new RecordsOfEmployeeAwardsAndSancti();
//
//        // 复制原始记录的所有字段
//        BeanUtils.copyProperties(originalRecord, newRecord);
//
//        // 获取最大单据编号，生成新的单据编号
//        RecordsOfEmployeeAwardsAndSancti max = baseMapper.selectMaxDocumentNumber();
//        String maxDocumentNumber = max != null ? max.getDocumentNumber() : "202500000";
//        String newDocumentNumber = String.valueOf(Integer.parseInt(maxDocumentNumber) + 1);
//
//        // 设置新记录的属性
//        newRecord.setId(null); // 清空ID，让数据库生成新的ID
//        newRecord.setOriginalId(originalRecord.getOriginalId() != null ? originalRecord.getOriginalId() : originalRecord.getId()); // 关联原始记录ID
//        newRecord.setVersion(originalRecord.getVersion() + 1); // 版本号递增
//        newRecord.setFirstLevelReviewer(corpMember.getNick());
//        newRecord.setModified(DateUtil.now());
//        newRecord.setStatus("待审核");
//        // 设置新的单据编号
//        newRecord.setDocumentNumber(newDocumentNumber);
//
//        // 更新用户提交的字段
//        if (body.getF3e2() != null) {
//            newRecord.setF3e2(body.getF3e2());
//        }
//        if (body.getF28c() != null) {
//            newRecord.setF28c(body.getF28c());
//            // 同时更新大写金额
//            newRecord.setAmountTotal1(convertToChineseYuan(body.getF28c()));
//        }
//        if (body.getLivePictures() != null) {
//            newRecord.setLivePictures(body.getLivePictures());
//        }
//        if (body.getLeadershipSignature() != null) {
//            newRecord.setLeadershipSignature(body.getLeadershipSignature());
//        }
//        if (body.getF90b() != null) {
//            newRecord.setF90b(body.getF90b());
//        }
//        if (body.getTypeOfAward() != null) {
//            newRecord.setTypeOfAward(body.getTypeOfAward());
//        }
//
//        // 保存新版本记录
//        return save(newRecord);
    }


    @Override
    @Transactional
    public boolean removeRecord(String id) {
        // 可以添加额外的删除逻辑，如记录删除日志等
        return removeById(id);
    }

    @Override
    public RecordsOfEmployeeAwardsAndSancti getHistoryVersions(String id) {
        LambdaQueryWrapper<RecordsOfEmployeeAwardsAndSancti> recordsOfEmployeeAwardsAndSanctiLambdaQueryWrapper = new LambdaQueryWrapper<>();
        recordsOfEmployeeAwardsAndSanctiLambdaQueryWrapper.eq(RecordsOfEmployeeAwardsAndSancti::getId, id);
        return recordsOfEmployeeAwardsAndSanctiMapper.selectOne(recordsOfEmployeeAwardsAndSanctiLambdaQueryWrapper);
//        // 首先获取记录
//        RecordsOfEmployeeAwardsAndSancti record = getById(id);
//        if (record == null) {
//            return new ArrayList<>();
//        }
//
//        // 确定原始记录ID
//        Integer originalId = record.getOriginalId() != null ?
//                record.getOriginalId() : record.getId();
//
//        // 查询该记录的所有历史版本，按版本号排序
//        List<RecordsOfEmployeeAwardsAndSancti> historyVersions = lambdaQuery()
//                .and(wrapper -> wrapper.eq(RecordsOfEmployeeAwardsAndSancti::getId, originalId)
//                        .or()
//                        .eq(RecordsOfEmployeeAwardsAndSancti::getOriginalId, originalId))
//                .orderByAsc(RecordsOfEmployeeAwardsAndSancti::getVersion)
//                .list();
//
//        // 转换用户信息
//        historyVersions.forEach(item -> {
//            // 转换 firstLevelReviewer 字段
//            String firstLevelReviewer = item.getFirstLevelReviewer();
//            if (StringUtils.hasText(firstLevelReviewer)) {
//                LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
//                wrapper.eq(CorpMember::getMemberId, firstLevelReviewer).last("limit 1");
//                CorpMember member = corpMemberMapper.selectOne(wrapper);
//                if (member != null && StringUtils.hasText(member.getNick())) {
//                    item.setFirstLevelReviewer(member.getNick());
//                }
//            }
//
//            // 转换 secondLevelReviewer 字段
//            String secondLevelReviewer = item.getSecondLevelReviewer();
//            if (StringUtils.hasText(secondLevelReviewer)) {
//                LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
//                wrapper.eq(CorpMember::getMemberId, secondLevelReviewer).last("limit 1");
//                CorpMember member = corpMemberMapper.selectOne(wrapper);
//                if (member != null && StringUtils.hasText(member.getNick())) {
//                    item.setSecondLevelReviewer(member.getNick());
//                }
//            }
//        });

//        return historyVersions;
    }


    /**
     * 将数字金额转换为中文大写金额
     *
     * @param amount 金额
     * @return 中文大写金额
     */
    private String convertToChineseYuan(BigDecimal amount) {
        if (amount == null) {
            return "";
        }

        String[] unit = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万亿"};
        String[] digit = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};

        String amountStr = amount.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        String integerPart = amountStr.split("\\.")[0]; // 整数部分
        String decimalPart = amountStr.split("\\.")[1]; // 小数部分

        StringBuilder result = new StringBuilder();

        // 处理整数部分
        if ("0".equals(integerPart)) {
            result.append("零");
        } else {
            int len = integerPart.length();
            for (int i = 0; i < len; i++) {
                int digitIndex = Integer.parseInt(String.valueOf(integerPart.charAt(i)));
                result.append(digit[digitIndex]);

                // 添加单位
                int unitIndex = len - i - 1;
                if (digitIndex != 0 || (i > 0 && integerPart.charAt(i - 1) != '0')) {
                    result.append(unit[unitIndex]);
                }
            }
        }

        // 处理小数部分
        result.append("元");
        if ("00".equals(decimalPart)) {
            result.append("整");
        } else {
            int jiao = Integer.parseInt(String.valueOf(decimalPart.charAt(0)));
            int fen = Integer.parseInt(String.valueOf(decimalPart.charAt(1)));

            if (jiao != 0) {
                result.append(digit[jiao]).append("角");
            }
            if (fen != 0) {
                result.append(digit[fen]).append("分");
            }
        }

        return result.toString();
    }


    /**
     * 根据员工姓名填充员工信息（车间、工种、班次等）
     *
     * @param body 奖惩记录对象
     */
    private void fillEmployeeInfoByName(RecordsOfEmployeeAwardsAndSancti body) {
        // 根据员工姓名查询员工档案

        Yg01employeefiles employee = yg01employeefilesMapper.selectById(body.getEmpId());
        String typeOfWork = employee.getTypeOfWork();
        String process = yg01employeefilesMapper.selectYgProcessByTypeOfWork(typeOfWork);
        body.setProcess(process);
        body.setName(employee.getName());
        String theHead = employee.getTheHead();

        List<String> livePictures = body.getLivePictures();
        List<PictureVo> pictureVoList=new ArrayList<>();
        if (CollectionUtil.isNotEmpty(livePictures)){
            for (String livePicture : livePictures) {
                PictureVo pictureVo = new PictureVo(livePicture);
                pictureVoList.add(pictureVo);
            }
        }
        String newLivePictures = JSONUtil.parse(pictureVoList).toString();
        body.setLivePicturesDto(newLivePictures);

        body.setGender(employee.getGender());
        //增加员工班组
        String class55 = employee.getClass55();
        String classes = "其他";
        if (class55.contains("甲")) {
            classes = "甲班";
        } else if (class55.contains("乙")) {
            classes = "乙班";
        } else if (class55.contains("丙")) {
            classes = "丙班";
        }
        body.setClasses(classes);
        body.setEmpPhone(employee.getContactCall());
        body.setEmpCode(employee.getCode()!=null?employee.getCode().toString():"");
        Integer staffId = employee.getId();

        // 填充从员工档案中可以直接获取的信息
        if (body.getWorkshop() == null && employee.getSector() != null) {
            body.setWorkshop(employee.getSector());
        }

        if (body.getFe97() == null && employee.getTypeOfWork() != null) {
            body.setFe97(employee.getTypeOfWork());
        }

        // 根据员工ID查询排班确认信息
        if (staffId != null) {
            ProPersonnelStandConfirm queryConfirm = new ProPersonnelStandConfirm();
            queryConfirm.setStaffId(staffId);
            List<ProPersonnelStandConfirm> confirmList = employeeFilesMapper.selectByCondition(queryConfirm);

            // 如果找到了排班确认信息，则填充车间、工种、班次等字段
            if (confirmList != null && !confirmList.isEmpty()) {
                ProPersonnelStandConfirm confirm = confirmList.get(0);

                // 只有当字段为空时才填充，避免覆盖用户传入的值
                if (body.getWorkshop() == null && confirm.getWorkshop() != null) {
                    body.setWorkshop(confirm.getWorkshop());
                }

                if (body.getFa90() == null && confirm.getClasses() != null) {
                    body.setFa90(confirm.getClasses());
                }
            }
        }
    }

    public static void main(String[] args) {
        String s="url:123456,url:456789,";
        String[] split = s.split(",");
        String s1 = split[0];
        int startIndex = s1.indexOf("url:")+4;
        int i = s1.length();
        System.out.println(s1.substring(startIndex, i));
    }
}
